package com.xpec.c4.game.common;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xpec.c4.service.common.ServiceInfo;
import com.xpec.c4.service.contexts.Contexts;
import com.xpec.c4.service.contexts.ScopeType;
import com.xpec.c4.service.h5common.H5ServiceInfo;
import com.xpec.c4.service.module.ModuleName;
import com.xpec.c4.service.module.ServerProperties;
import com.xpec.c4.service.module.common.PlayerCommonInfoManager;

/**
 * 自动GC的任务
 * 
 * @author lipeilin
 * @2011-6-17 上午11:01:08
 * 
 */
public class AutoGC implements Runnable {

	private static final Log log = LogFactory.getLog(AutoGC.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		
		if (log.isInfoEnabled() && ServerProperties.isTargetModule(PlayerCommonInfoManager.getInstance().getGatewayBySessionId(Contexts.getSessionID()), ModuleName.H5GATEWAY)) {
			log.info("auto gc! thread count:" + Thread.activeCount()
					+ " ContentSessionAmount:"
					+ Contexts.getContextSize(ScopeType.SESSION)
					+ " ServerSessionAmount:"
					+ H5ServiceInfo.getSessionCount());
		} else {
			log.info("auto gc! thread count:" + Thread.activeCount()
					+ " ContentSessionAmount:"
					+ Contexts.getContextSize(ScopeType.SESSION)
					+ " ServerSessionAmount:"
					+ ServiceInfo.getSessionCount());
		}
		
		long st = System.nanoTime();
		Runtime runtime = Runtime.getRuntime() ;
		runtime.gc();
		long et = System.nanoTime() - st;
		
		long memory = (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024);
		
		if (log.isInfoEnabled()) {
			log.info(ServerProperties.localServer + " GC Spend time:"
					+ ((double) et / 1000000000.0f) + "sec.    totalMem:"
					+ (runtime.totalMemory()/(1024*1024)) + "MB  freeMem:"
					+ (runtime.freeMemory()/(1024*1024)) + "MB  UsedMem:" + memory + "MB");
		}

		// 打印 zone的信息
/*		
		List<Zone> zones = ZoneContainer.instance().getAllLocalZone();
		log.info("Zone message:" + zones.size());
		for (Zone zone : zones) {
			StringBuilder value = new StringBuilder();
			value.append("zoneID:" + zone.getId() + "|playerAmount:"
					+ zone.getPlayerGuids().size() + "|npcAmount:"
					+ zone.getNpcs().size() + "|corpseAmount:"
					+ zone.getCorpses().size() + "|collectionPointAmount:"
					+ zone.getCollectionPoints().size());
			log.info(value);
		}

		HashMap<String, Integer> zonePlayerAmounts = new HashMap<String, Integer>(ZoneContainer.getZonePlayerAmounts());
		log.info("ZonePlayerAmounts:" + zonePlayerAmounts.size());
		for (Map.Entry<String, Integer> zone : zonePlayerAmounts.entrySet()) {
			StringBuilder value = new StringBuilder();
			value.append("zoneID:" + zone.getKey() + " playerAmount:"
					+ zone.getValue());
			log.info(value);
		}
*/
	}
}
